package com.lizhen;

/*
 * @Title WebSocketDemo
 * @Description About WebSocketDemo mechanism
 * @Company com.lizhen
 * @author lizhen
 */

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket")
public class WebSocketDemo {

    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WebSocketDemo> webSocketSet = new CopyOnWriteArraySet<>();
    private Session session;

    public static synchronized void addOnlineCount() {
        WebSocketDemo.onlineCount++;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void subOnlineCount() {
        WebSocketDemo.onlineCount--;
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();

        System.out.println("当前在线连接数是" + getOnlineCount());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();

        System.out.println("当前在线连接数是" + getOnlineCount());
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        // this.session.getAsyncRemote().sendText(message);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("当前消息是" + message);

        for (WebSocketDemo item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("连接出错");

        error.printStackTrace();
    }

}
